package com.example.mybatispermission.controller;

import com.example.mybatispermission.entry.Role;
import com.example.mybatispermission.entry.User;
import com.example.mybatispermission.mapper.RoleMapper;
import com.example.mybatispermission.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("user")
@AllArgsConstructor
public class UserController {
    private UserMapper userMapper;
    private RoleMapper roleMapper;
    private static final Integer userRoleId = 3;
    @PostMapping("login")
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException e) {
            return username + " 未注册";
        } catch (IncorrectCredentialsException e) {
            return "密码与用户名不符";
        }
        response.sendRedirect("/");
        return "登录成功";
    }
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        subject.logout();
        return user.getNickname() + " 退出登录";
    }

    @PostMapping("register")
    public String register(User user) {
        String salt = String.format("%06d", (int)(Math.random() * 1000000));
        user.setPasswordSalt(salt);
        Md5Hash hash = new Md5Hash(user.getPassword(), new SimpleByteSource(salt));
        user.setPassword(hash.toHex());
        userMapper.insert(user);
        Role role = roleMapper.selectById(userRoleId);
        userMapper.bindRole(user, role);
        return "注册成功";
    }
}
